package com.atguigu.yygh.user.service.impl;

import com.atguigu.yygh.common.exception.YyghException;
import com.atguigu.yygh.common.helper.JwtHelper;
import com.atguigu.yygh.common.result.ResultCodeEnum;
import com.atguigu.yygh.model.hosp.HospitalSet;
import com.atguigu.yygh.model.user.UserInfo;
import com.atguigu.yygh.user.mapper.UserMapper;
import com.atguigu.yygh.user.service.UserService;
import com.atguigu.yygh.vo.user.LoginVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, UserInfo> implements UserService {

   @Autowired
   private  UserMapper userMapper;
   @Autowired
   private RedisTemplate<String ,String> redisTemplate;

    @Override
    public Map< String, Object> loginUser(LoginVo loginVo) {

        //从loginVo获取输入的手机号和验证码
        String phone = loginVo.getPhone();
        String code = loginVo.getCode();
        if(StringUtils.isEmpty(phone)||StringUtils.isEmpty(code)){

            throw new YyghException(ResultCodeEnum.PARAM_ERROR);
        }

        //TODO 判断手机验证码和输入的验证码是否一致


        String redisCode = redisTemplate.opsForValue().get(phone);
if(!code.equals(redisCode)){

    throw new YyghException(ResultCodeEnum.CODE_ERROR);
}



        //判断我们是否是第一次登入: 更具手机号查询数据库，如果不存在相同手机号就是第一次登入
 QueryWrapper<UserInfo> wrapper=new QueryWrapper<>();
        wrapper.eq("phone",phone);

        UserInfo userInfo = baseMapper.selectOne(wrapper);
        if(userInfo==null){
                     userInfo=new UserInfo();
                     userInfo.setName(" ");
                     userInfo.setPhone(phone);
                     userInfo.setStatus(1);

                     baseMapper.insert(userInfo);

        }
        //校验是否被禁用
        if(userInfo.getStatus()==0){

       throw new YyghException(ResultCodeEnum.LOGIN_DISABLED_ERROR);
        }



        //不是第一次 直接登入


   //返回登录信息

        //返回登录用户名

        //返回token信息
 Map<String,Object> map=new HashMap<>();


        String name=userInfo.getName();
         if(StringUtils.isEmpty(name)){
             name=userInfo.getNickName();
         }
    if(StringUtils.isEmpty(name)){

        name=userInfo.getPhone();
    }

    map.put("name",name);

    //TODO  token生成
        String token = JwtHelper.createToken(userInfo.getId(), name);
        map.put("token",token);

        return map;
    }
}
